<template>
  <div class="after-sale-detail">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>售后详情</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>

      <div v-loading="loading">
        <!-- 售后基本信息 -->
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="售后单号">{{ afterSaleInfo.afterSaleNo }}</el-descriptions-item>
          <el-descriptions-item label="关联订单号">{{ afterSaleInfo.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDate(afterSaleInfo.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="售后状态">
            <el-tag :type="getStatusType(afterSaleInfo.status)">
              {{ getStatusText(afterSaleInfo.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="售后类型">
            <el-tag :type="getTypeTag(afterSaleInfo.type)">
              {{ getTypeText(afterSaleInfo.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请原因">{{ afterSaleInfo.reason }}</el-descriptions-item>
        </el-descriptions>

        <!-- 商品信息 -->
        <div class="section-title">商品信息</div>
        <el-table :data="afterSaleInfo.items || []" border style="width: 100%">
          <el-table-column prop="itemName" label="商品名称" min-width="200"></el-table-column>
          <el-table-column prop="price" label="单价" width="120">
            <template #default="{ row }">
              ¥{{ formatNumber(row.price) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              ¥{{ formatNumber(row.price * row.quantity) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 用户上传的凭证照片 -->
        <div v-if="afterSaleInfo.images && afterSaleInfo.images.length > 0">
          <div class="section-title">凭证照片</div>
          <div class="images-container">
            <el-image
              v-for="(img, index) in afterSaleInfo.images"
              :key="index"
              :src="img"
              :preview-src-list="afterSaleInfo.images"
              fit="cover"
              class="evidence-image"
            ></el-image>
          </div>
        </div>

        <!-- 处理表单 -->
        <div class="section-title">处理操作</div>
        <el-form ref="formRef" :model="form" label-width="120px" v-if="afterSaleInfo.status === 'PENDING'">
          <el-form-item label="处理结果" prop="result">
            <el-radio-group v-model="form.result">
              <el-radio label="APPROVED">同意</el-radio>
              <el-radio label="REJECTED">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="处理备注" prop="remark">
            <el-input
              type="textarea"
              v-model="form.remark"
              placeholder="请输入处理备注"
              :rows="3"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">提交处理</el-button>
          </el-form-item>
        </el-form>

        <!-- 已处理的结果展示 -->
        <el-descriptions v-else :column="1" border>
          <el-descriptions-item label="处理结果">
            <el-tag :type="afterSaleInfo.result === 'APPROVED' ? 'success' : 'danger'">
              {{ afterSaleInfo.result === 'APPROVED' ? '已同意' : '已拒绝' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理时间">{{ formatDate(afterSaleInfo.handleTime) }}</el-descriptions-item>
          <el-descriptions-item label="处理备注">{{ afterSaleInfo.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import service from '@/utils/request'

const route = useRoute()
const router = useRouter()
const afterSaleId = route.params.id

const loading = ref(false)
const submitting = ref(false)
const afterSaleInfo = ref({})

const form = ref({
  result: 'APPROVED',
  remark: ''
})

// 获取售后详情
const getAfterSaleDetail = async () => {
  loading.value = true
  try {
    const res = await service.get(`/merchant/after_sale/${afterSaleId}`)
    if (res) {
      afterSaleInfo.value = res
    }
  } catch (error) {
    console.error('获取售后详情失败:', error)
    ElMessage.error('获取售后详情失败')
  } finally {
    loading.value = false
  }
}

// 返回列表
const goBack = () => {
  router.push('/merchant/after_sale')
}

// 提交处理
const handleSubmit = async () => {
  if (!form.value.remark) {
    ElMessage.warning('请输入处理备注')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认${form.value.result === 'APPROVED' ? '同意' : '拒绝'}此售后申请？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    submitting.value = true
    await service.post(`/merchant/after_sale/${afterSaleId}/handle`, form.value)
    ElMessage.success('处理成功')
    getAfterSaleDetail() // 刷新数据
  } catch (error) {
    if (error === 'cancel') return
    console.error('处理售后失败:', error)
    ElMessage.error('处理售后失败')
  } finally {
    submitting.value = false
  }
}

// 格式化数字
const formatNumber = (num) => {
  const n = Number(num)
  if (isNaN(n)) return '0.00'
  return n.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  try {
    const d = new Date(date)
    return d.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return '日期格式错误'
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger',
    'CLOSED': 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'PENDING': '待处理',
    'APPROVED': '已同意',
    'REJECTED': '已拒绝',
    'CLOSED': '已关闭'
  }
  return textMap[status] || '未知状态'
}

// 获取售后类型标签
const getTypeTag = (type) => {
  const typeMap = {
    'REFUND': 'danger',
    'EXCHANGE': 'warning',
    'RETURN': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取售后类型文本
const getTypeText = (type) => {
  const textMap = {
    'REFUND': '仅退款',
    'EXCHANGE': '换货',
    'RETURN': '退货退款'
  }
  return textMap[type] || '未知类型'
}

onMounted(() => {
  getAfterSaleDetail()
})
</script>

<style scoped>
.after-sale-detail {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  margin: 20px 0 10px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  border-left: 3px solid #409EFF;
  padding-left: 10px;
}

.images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 10px 0;
}

.evidence-image {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}
</style> 